var netcore = require('../../../utils/network.js')
var tripleDes = require('../../../utils/CKCrypto.js')
var wallet=require('../../mywallet/model/WalletModel.js')
function getOrder(payChannel, payType, goodsId, goodsType, bk,callBack) {
  var openId = getApp().globalData.openId
  var params = new Map();
  params.set("payChannel", payChannel)
  params.set("payType", payType)
  params.set("goodsId", tripleDes.enCode(goodsId))
  params.set("goodsType", goodsType)
  params.set("lat", getApp().globalData.userLocationInfo.lat)
  params.set("lng", getApp().globalData.userLocationInfo.lng)
  params.set("origin", "xcs")
  var _action = "wx/pay.do"
  if (bk != null && typeof (bk) != undefined && bk.length > 0) {
    params.set("bk", bk)
    _action = "wx/shareH5Pay.do"
  }
  if (openId == null || openId.length <= 0 || typeof (openId) =='undefined'){
    wallet.getOpenId(function (openId) {
      if (openId != null) {
        getApp().globalData.openId = openId
        params.set("openid", tripleDes.enCode(openId))
        netcore.requestPost(_action, params, function (success) {
          callBack(success)
        }, function (code, errMsg) {
          wx.showToast({
            title: errMsg,
            duration: 3000
          })
        })
      }
    })
  }else{
    params.set("openid", tripleDes.enCode(openId))  
    netcore.requestPost(_action, params, function (success) {
      callBack(success)
    }, function (code, errMsg) {
      // wx.showToast({
      //   title: errMsg,
      //   duration: 3000
      // })
      wx.showModal({
        title: "购买失败",
        content: errMsg,
        success: function (res) {
          if (res.cancel) {
            //点击取消,默认隐藏弹框
          } else {
            //点击确定
            wx.redirectTo({
              url: '/pages/recharge/recharge'
            })
          }
        },
       
        duration: 3000
      })
    })
  }
  
  
}
function _pay(_timeStamp, _nonceStr, prepayId, _paySign, callBack){
  wx.requestPayment({
    timeStamp: _timeStamp,
    nonceStr: _nonceStr,
    package: prepayId,//Sign=WXPay
    signType: 'MD5',
    paySign: _paySign,
    success: function (res) {
      console.log("微信支付:%o", res)
      callBack(0, res)
    },
    fail: function (error) {
      console.log("微信支付:%o", error)
      callBack(-1, error)
    },
    complete: function (res) {
      console.log("微信支付流程完成")
    }
  })
}
module.exports = {
  getOrder: getOrder,
  pay: _pay
}